package cn.com.smart.module.system.user.controller;

import cn.com.smart.common.utils.Cache;
import cn.com.smart.common.utils.JWTUtil;
import cn.com.smart.framework.shiro.service.PasswordService;
import cn.com.smart.framework.web.controller.BaseController;
import cn.com.smart.framework.web.domain.AjaxResult;
import cn.com.smart.module.system.menu.service.IMenuService;
import cn.com.smart.module.system.user.domain.User;
import cn.com.smart.module.system.user.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.Set;

@Controller
@RequestMapping("/app")
public class AppLoginController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private IMenuService menuService;

    @ApiOperation(value = "app登陆接口",httpMethod = "POST")
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult appLogin(String  username, String password){
        AjaxResult result=new AjaxResult();
        // 功能列表
        Set<String> menus = new HashSet<String>();
        if(username==null||password==null){
            return new AjaxResult(AjaxResult.Type.ERROR,"账号或密码不能为空");
        }
        // 查询用户信息
        User user = userService.selectUserByLoginName(username);
        if(user==null||!user.getPassword().equals(passwordService.encryptPassword(username,password,user.getSalt()))){
         return new AjaxResult(AjaxResult.Type.ERROR,"账号或密码错误");
        }else {
            //将用户菜单权限放入缓存
            menus = menuService.selectPermsByUserId(user.getUserId());
            Cache.put(user.getUserId().toString(),menus);
            String token= JWTUtil.createToken(user);
            return new AjaxResult(AjaxResult.Type.SUCCESS,"登陆成功",token);
        }
    }
}
